package com.tangxz.generate_code.utils.base;

//import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangxz.generate_code.utils.ReflexUtil;
import com.tangxz.generate_code.utils.page.PageUtils;
import com.tangxz.generate_code.utils.page.Query;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2021/12/14 20:21
 */
public class MyBaseServiceImpl<M extends MyBaseMapper<T>, T> extends ServiceImpl<M, T> implements MyBaseService<T> {

    @Autowired
    M mapper;

    @Override
    public Integer insertOrBackId(T t) {
        mapper.insertOrBackId(t);
        return Integer.valueOf(ReflexUtil.getFieldValueByFieldName("id", t));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<T> queryWrapper = getQueryWrapper(params);
        IPage<T> page = this.page(
                new Query<T>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<T> listQuery(Map<String, Object> params) {
        QueryWrapper<T> queryWrapper = getQueryWrapper(params);
        return list(queryWrapper);
    }

    private QueryWrapper<T> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (params.containsKey("eq")) {
            // TODO 注释需要解开，这里给批量查询添加了一个eq，全值匹配功能，入参在MyBaseController里面写有注释

//            Map eqs = JSON.parseObject(String.valueOf(params.get("eq")));
//            for (Object key : eqs.keySet()) {
//                queryWrapper = queryWrapper.eq(String.valueOf(key), eqs.get(key));
//            }
        }
        return queryWrapper;
    }
}
